<template>
  <div id="user_certification">
    <div v-if="headIos" style="z-index:9; width: 100%; height: 20px;background: white;position: fixed;top: 0;"></div>
    <div class="">
      <k-header headTitle="企业认证" rightTitle="跳过" v-if="nulls" @rightClick="skip()"></k-header>
      <k-header headTitle="企业认证" goBack="true" v-else></k-header>
    </div>
    <div class="certifi_list" :class="headIos?'side-fixd-ios':'side-fixed'">
      <group>
        <cell title="公司信息" class="basecompany" />
        <div class="seach_prompt">
          <cell title="公司名称"><!--  @keyup="get(event)"
              @keydown.up.prevent="selectUp"
              @keydown.down.prevent="selectDown"
              "-->
            <input type="text" solt="value" placeholder="请输入公司名称(必填)" class='company_name'
              v-model="keyword"
              :data-id="companyId"
              @blur="changeCount()"
            />
          </cell>
          <ul class="prompt_list" v-show="acstate">
            <li v-for="value in myData" @click.stop.prevent="prompt_true(value.companyId, value.fullName, value.companiesNum)" :key="value.fullName">
              <span>{{ value.fullName }}</span>
              <span class="prompt_state">已认证</span>
            </li>
          </ul>
        </div>
        <cell title="公司规模">
          <input type="number" solt="value" placeholder="请输入公司人数(必填)" class='company_name' v-model="scale" @change="changet()" />
        </cell>
        <cell title="公司地址" v-if="judadress">
          <input type="text" solt="value" placeholder="请输入公司地址" class='company_name' v-model="companyadres" @change="changet()" />
        </cell>
        <cell title="公司电话" v-if="judtel">
          <input type="text" solt="value" placeholder="请输入公司电话" class='company_name' v-model="companytel" @change="changet()" />
        </cell>
        <cell title="职位">
          <input type="text" solt="value" placeholder="请输入职位名称(必填)" class='company_name' v-model="poname" @change="changet()" />
        </cell>
      </group>
      <div class="certifi_data">
        <div class="certifi_data_head">认证资料{{companyphoto?'(二选一)':'(必填)'}}</div>
        <div class="upload">
          <input
            type="file"
            class="profileinfopanel-upload"
            @change="uploadAvatar('workcard')"
            ref="inputer"
            id="workcard"
            name="uploadFile"

          />
          <div class="upbox">
            <img src="../../assets/img/center/addupload.png" alt="" class="symboladd">  <!-- accept="image/*|MIME_type" -->
            <p>工牌/名片</p>
          </div>
          <img :src="dataUrl" alt="" class="previewadd">
        </div>
        <div class="upload" v-if="companyphoto">
          <input
            type="file"
            class="profileinfopanel-upload"
            @change="uploadAvatar('companycard')"
            ref="inpute"
            id="companycard"
            name="uploadFile"
          />
          <div class="upbox">
            <img src="../../assets/img/center/addupload.png" alt="" class="symboladd">
            <p>企业营业执照</p>
          </div>
          <img :src="companyUrl" alt="" class="previewadd">
        </div>
      </div>
    </div>
    <toast v-model="showPositionValue" type="text" width="100%" :time="1800" is-show-mask :text="massg" position="bottom"></toast>
    <div class="applygray" @click="prompt_tur()" :class="{ applyfor: applyt }">提交</div>
    <!-- <div class="applyfor" @click="prompt_tur()">提交</div> -->
  </div>
</template>

<style scoped>
  ul,li {
    list-style: none;
  }
  #user_certification {
    background-color: rgb(245,245,245);
  }
  .previewadd {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    /* z-index: 11; */
  }
  .profileinfopanel-upload{
    display: block;
    width: 100%;
    height: 100%;
    position: absolute;
    opacity: 0;
    top: 0;
    left: 0;
    z-index: 10;
  }
  .upload {
    position: relative;
    width: 90%;
    height: 160px;
    /* border: 1px solid red;*/
    background-color: #fff;
    margin: 0 auto;
    margin-bottom: 1rem;
    text-align: center;
    border-radius: 4px;
    box-shadow: 2px 2px 2px #d8d8d8;
  }
  .upbox {
    position: relative;
    top: 3.5rem;
  }
  .upbox p {
    margin-top: 1.6rem;
    font-size: 1.4rem;
    color: #808080;
    font-family: PingFangSC-Regular;
  }
  .symboladd {
    width: 4.8rem;
    height: 4.8rem;
  }
  .certifi_list {
    padding: 45px 0;
    background: #f5f5f5;
  }
  .side-fixd-ios {
    padding-top: 65px;
  }
  .basecompany {
    background-color: #f5f5f5;
  }
  .weui-cell {
    padding: 0 .8rem !important;
    height: 44px;
  }
  .company_name {
    text-align: right;
    border: none;
    outline: none;
  }
  .certifi_data_head {
    height: 44px;
    line-height: 46px;
    padding: 0 .8rem;
    font-size: 1.4rem;
    color: #808080;
  }
  .seach_prompt {
    position: relative;
  }
  .prompt_list {
    position: absolute;
    /* bottom: -40px; */
    right: .8rem;
    background-color: #fff;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    z-index: 999;
    box-shadow: #ccc 2px 4px 3px;
  }
  .active {
    display: none;
  }
  .prompt_list li {
    padding: .8rem 1.8rem;
  }
  .prompt_state {
    color: #6ce26c;
    margin-left: 2rem;
  }
  .applygray {
    width: 100%;
    height: 49px;
    background-color: #d8d8d8;
    position: fixed;
    z-index: 15;
    bottom: 0;
    left: 0;
    color: #fff;
    text-align: center;
    line-height: 49px;
    font-size: 1.4rem;
  }
  .applyfor {
    background-color: #F89721;
  }
</style>

<script>
import kHeader from '../common/head'
import { Group, Cell,Toast } from 'vux'
import util from '../../libs/util'
import VueImgInputer from 'vue-img-inputer'
import EXIF from '../../libs/exif'
export default {
  name: 'usercertification',
  data() {
    return {
      myData: [],
      keyword: '', // 企业名称
      companyId: '', // 企业id
      now: -1,
      acstate: false,
      scale: '',
      poname: '',
      noting: '',
      companyadres: '',
      companytel: '',
      nulls: true,
      judadress: true,
      judtel: true,
      applyt: false,
      companyphoto: true,
      dataUrl: '', //工牌预览
      companyUrl: '', //营业执照预览
      file: [],
      photosucc: false,  //判断工作牌是否上传成功
      comsucc: false, //判断营业照是否上传成功
      showPositionValue: false,
      companie: '',
      compictrue: '',
      workerpictrue: '',
      adds: '',
      headIos: false,
      canvas: '',
      ctx: '',
      massg: ''
    }
  },
  components: {
    kHeader,
    Group,
    Cell,
    VueImgInputer,
    Toast
  },
  methods: {
    get(k) { // 搜索提
      let that = this;
      var url = '/lblsapp-h5/v2/memberInfo/getFullNameList.json';
      if(k != ''){
          let data = { fullName: that.keyword }
          util.ajax.post(url, data).then(function(stats) {
            that.myData = stats.data.res.data;
            that.acstate = true;
            // if (that.myData.length != 0 && that.keyword != "") { // 如果搜索提示不为空并且input值不为空
            //   for (let i = 0; i < that.myData.length; i++) {
            //     if (that.myData[i].fullName == that.keyword) {
            //       that.acstate = false;
            //     }
            //   };
            // }else {
            //   that.acstate = true;
            // }
          }).catch(function(error) {
            console.log(error)
          })
      } else {
        that.acstate = false;
      }
    },
    prompt_true(ips, fulln, companie) {  //搜索提示列表点击

      this.acstate = false;
      this.keyword = fulln;
      this.adds = fulln;
      this.companyId = ips;
      this.judadress = false;
      this.judtel = false;
      this.companyphoto = false;
      this.scale = companie;

    },
    imgPreview(file,m) {  //图片预览函数
      let self = this;
      // 看支持不支持FileReader
      if (!file || !window.FileReader) return;
      if (/^image/.test(file.type)) {
        // 创建一个reader
        var reader = new FileReader();
        // 将图片将转成 base64 格式
        reader.readAsDataURL(file);
        // 读取成功后的回调
        reader.onloadend = function() {
          if(m == 'workcard'){
            self.dataUrl = this.result;
//            假预览
          } else if (m == 'companycard'){
            self.companyUrl = this.result;
          }
        }
      }
    },
    uploadAvatar(y) { //图片上传以及转换
      let that = this;
      var inpu = document.getElementById(y);
      var reader = new FileReader();
      let sdata = {};
      // 通过DOM取文件数据
      this.file = inpu.files[0];
//      console.log(this.file.size);
      let str = this.file.name;
      var reg = /(.*)\.([^\.]+)/g;
      let strs = str.replace(reg,'$1');
      sdata.fileName = strs;
      let drl = 'lblsapp-h5/v2/upload/saveFile.json';
      reader.readAsDataURL(this.file);
      reader.onload = function() {
        var oreader = new FileReader();
          var image = new Image();
          image.src = this.result;
          image.onload = function() {
            that.canvas = document.createElement("canvas");
            that.ctx = that.canvas.getContext("2d");

            var r,expectWidth,base64,size = (inpu.files[0].size)/1024000;
            EXIF.getData(image, function() {
              r = EXIF.getTag(this, 'Orientation');
            });
            if (size > 1) {
              base64 = that.compressImage(image, 900, r);
            } else {
              base64 = image.src;
            }
            sdata.base64String = base64.split(',')[1];
            util.ajax.post(drl,sdata).then(function(stats){
              if(stats.data.code == '0'){
                if(y == 'workcard'){
                  that.photosucc = true;
                  that.workerpictrue = stats.data.res.msg;
                };
                if(y == 'companycard'){
                  that.comsucc = true;
                  that.compictrue = stats.data.res.msg;
                };
                that.changet();
                that.imgPreview(that.file, y);
              };

            }).catch(function(error){
              console.log(error);
            })
          }
      }
    },
    compressImage(img, compressWidth, k) { //处理f翻转
      var self = this;
//      self.canvas = document.getElementById("canvas");
//      self.ctx = self.canvas.getContext("2d");
      var imgWidth = img.naturalWidth;
      var imgHeight = img.naturalHeight;
      var scale = imgWidth / imgHeight;
      var ctxImgHeight;
      if (k == 8) {
        ctxImgHeight = compressWidth * scale;
        self.canvas.width = compressWidth;
        self.canvas.height = ctxImgHeight;
        self.ctx.clearRect(0, 0, ctxImgHeight, compressWidth);
        self.ctx.fillStyle = "#fff";
        self.ctx.fillRect(0, 0, ctxImgHeight, compressWidth);
        self.ctx.rotate(270 * Math.PI / 180);
        self.ctx.drawImage(img, 0, 0, -ctxImgHeight, compressWidth);
      } else if (k == 6) {
        ctxImgHeight = compressWidth * scale;
        self.canvas.width = compressWidth;
        self.canvas.height = ctxImgHeight;
        self.ctx.clearRect(0, 0, ctxImgHeight, compressWidth);
        self.ctx.fillStyle = "#fff";
        self.ctx.fillRect(0, 0, ctxImgHeight, compressWidth);
        self.ctx.rotate(90 * Math.PI / 180);
        self.ctx.drawImage(img, 0, 0, ctxImgHeight, -compressWidth);

      } else if (k == 3) {
        ctxImgHeight = compressWidth / scale;
        self.canvas.width = compressWidth;
        self.canvas.height = ctxImgHeight;
        self.ctx.clearRect(0, 0, compressWidth, ctxImgHeight);
        self.ctx.fillStyle = "#fff";
        self.ctx.fillRect(0, 0, compressWidth, ctxImgHeight);
        self.ctx.rotate(180 * Math.PI / 180);
        self.ctx.drawImage(img, 0, 0, -compressWidth, -ctxImgHeight);
      } else {
        ctxImgHeight = compressWidth / scale;
        self.canvas.width = compressWidth;
        self.canvas.height = ctxImgHeight;
        self.ctx.clearRect(0, 0, compressWidth, ctxImgHeight);
        self.ctx.fillStyle = "#fff";
        self.ctx.fillRect(0, 0, compressWidth, ctxImgHeight);
        self.ctx.drawImage(img, 0, 0, compressWidth, ctxImgHeight);
      }
      var base64 = self.canvas.toDataURL("image/jpeg", 0.98);
      return base64;
    },
    changeCount() { // 匹配选中的公司 是已认证过的
      this.acstate = false;
      if(this.myData.length != 0 && this.keyword != ""){ // 如果搜索提示不为空并且input值不为空
        for(let i=0; i<this.myData.length; i++){
          if(this.myData[i].fullName == this.keyword ){
            this.judadress = false;
            this.judtel = false;
            this.companyphoto = false;
            return;
          } else {
            this.judadress = true;
            this.judtel = true;
            this.companyphoto = true;
            this.scale = '';
          }
        };
      } else {
        this.judadress = true;
        this.judtel = true;
        this.companyphoto = true;
      }
    },
    prompt_tur: function() {
      this.changet();
      console.log(this.applyt);
      let prompt = {
        fullName: '',
        qyyyzzPhoto: '',
        companiesNum: '',
        position: '',
        companyInfoId: '',
        workCard: '',
        phone: '',
      };
      let drl = 'lblsapp-h5/v2/memberInfo/sumbToCompauth.json';
      prompt.fullName = this.keyword;
      prompt.position = this.poname;
      if(this.judadress == false){ //匹配到公司情况下
        prompt.companyInfoId = this.companyId;
        prompt.companiesNum = this.scale;
        prompt.workCard = this.workerpictrue;
      }else {
        prompt.companyadres = this.companyadres;
        prompt.phone = this.companytel;
        prompt.companiesNum = this.scale;
        prompt.qyyyzzPhoto = this.compictrue;
        prompt.workCard = this.workerpictrue;
      };
      if(this.applyt){
        var that = this;
          util.ajax.post(drl,prompt).then(function(stats){
            if(stats.data.code == '0'){
              that.$router.push('/worker');
            }else if(stats.data.code == '1'){
              that.massg = stats.data.res.msg;
              that.showPositionValue = true;
            }
          }).catch(function(error){
            console.log(error);
          });
        }else {
        this.myTost('请补全必填信息')
        if(this.judadress == false){ // 如果匹配到公司
          if (!this.keyword) {
            this.myTost('请输入公司名称')
          } else {
            if(!this.scale){
              this.myTost('请输入正确公司人数(仅限数字)')
            }else {
              if(!this.poname){
                this.myTost('请输入职位')
              }else {
                if(!this.photosucc){
                  this.myTost('请上传工牌/名片')
                }
              }
            }
          }
        }else {
          if (!this.keyword) {
            this.myTost('请输入公司名称')
          } else {
            if(!this.scale){
              this.myTost('请输入正确公司人数(仅限数字)')
            }else {
              if(!this.poname){
                this.myTost('请输入职位')
              }else {
                if(!(this.photosucc || this.comsucc)){
                  this.myTost('请上传认证资料')
                }
              }
            }
          }
        }
      }
    },
    myTost(info){
      this.$vux.toast.show({
        type:'text',
        text: info,
        time:'1500',
        position:'middle',
        width:'15em'
      })
    },
    fetchDate: function() { // 判断是否为首次登录注册进入
      if(this.$route.query.moths){
        this.nulls = true;
      }else {
        this.nulls = false;
      }
    },
    skip: function() {//跳过到首页
      var that = this;
      this.$vux.confirm.show({
        title: '',
        content: '是否要跳过认证',
        onShow () {

        },
        onHide () {

        },
        onCancel () {

        },
        onConfirm () {
          that.$router.push('/worker');
        }
      })

    },
    changet: function() { // 校验是否可提交
      if(this.judadress == false){ // 如果匹配到公司
        if (this.keyword && this.scale && this.poname && this.photosucc) {
          this.applyt = true;
        } else {
          this.applyt = false;
        }
      }else {
        if (this.keyword && this.scale && this.poname && this.photosucc || this.comsucc) {
          this.applyt = true;
        } else {
          this.applyt = false;
        }
      }

    }
  },
  created() {
    if (window.navigator.userAgent.indexOf('LBLSIOS') > -1) {
      this.headIos = true;
    }
    this.fetchDate();
  },
  watch: {
    'keyword': function(val, oldVal) {
      if(val != this.adds){
        this.get(val);
      }
      if(val == ''){
        this.acstate = '';
        this.scale = '';
        this.adds = '';
      }
    }
  },
}
</script>


